class GridEvent < ActiveRecord::Base

  unloadable #can't dup NilClass in task_scheduler.rb fix

  before_create :cancel_empty

  has_and_belongs_to_many :users, :after_remove => :delete_orphan
  belongs_to :grid

  def self.to_json(events)
    "[#{events.collect {|event| event.data}.join(', ')}]"
  end

  def self.find_waiting_events(user_id, grid_id)
    self.find_by_sql ['select * from grid_events where exists (select * from grid_events_users where user_id=?)
                                     and grid_id=?', user_id, grid_id]
  end

  private

  def delete_orphan(user)
    if (users.empty?)
      destroy()
    end
  end

  def cancel_empty
    return false if self.users.empty?
  end

end
